package com.jcfk.system.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.common.business.enums.AvailableStatus;
import com.jcfk.common.business.log.annotation.RequestLogHeader;
import com.jcfk.common.business.utils.DataBindHelper;
import com.jcfk.common.core.exception.CustomException;
import com.jcfk.common.core.utils.IdUtils;
import com.jcfk.common.security.annotation.AllowAnonymous;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.ReqPageParam;
import com.jcfk.common.web.domain.RetPage;
import com.jcfk.common.web.domain.RetResult;

import com.jcfk.system.domain.dto.AnnexesFileDTO;
import com.jcfk.system.domain.po.SysAppVersion;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.dongliu.apk.parser.ApkFile;
import net.dongliu.apk.parser.bean.ApkMeta;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

import com.jcfk.system.domain.query.SysAppVersionQuery;
import com.jcfk.system.domain.dto.SysAppVersionDTO;
import com.jcfk.system.service.SysAppVersionService;
import com.jcfk.common.core.utils.ExcelUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * APP版本表
 *
 * @author awei
 * @email 522891237@gqq.com
 * @date 2024-01-22
 */
@Api(tags = {"APP版本表管理"})
@RestController
@RequestMapping("sysappversion")
public class SysAppVersionController {
    @Autowired
    private SysAppVersionService sysAppVersionService;


    /**
     * 存储路径
     */
    @Value("${file.storagePath:}")
    private String storagePath;

    /**
     * 分页列表
     */
    @ApiImplicitParams({@ApiImplicitParam(paramType = "body", dataType = "ReqPageParam<SysAppVersionQuery>", name = "requestParam", value = "", required = true)})
    @ApiOperation("分页查询APP版本表")
    @PostMapping("/queryByPage")
    @ResponseBody
    public RetPage<SysAppVersionDTO> queryByPage(@RequestBody ReqPageParam<SysAppVersionQuery> requestParam) {
        DataPage<SysAppVersionDTO> page = new DataPage<SysAppVersionDTO>((long) requestParam.getCurrent(), (long) requestParam.getSize(), requestParam.getSort().getOrderItem(), SysAppVersionDTO.class);
        page = sysAppVersionService.queryByPage(page, requestParam.getData());

        return new RetPage<>(page);
    }


    /**
     * APP版本表
     * 根据id 查询详情
     */
    @ApiOperation("查询APP版本表")
    @GetMapping("/get/{id}")
    @ResponseBody
    public RetResult<SysAppVersionDTO> get(@PathVariable("id") String id) {
        SysAppVersionDTO item = sysAppVersionService.get(id);
        return RetResult.ok(item);
    }

    /**
     * 添加/更新管理APP版本表
     */
    @ApiOperation("保存APP版本表")
    @PostMapping("/save")
    @ResponseBody
    @RequestLogHeader(modular = "APP版本表管理", businessType = "保存")
    public RetResult<?> save(@RequestBody @Valid SysAppVersionDTO sysAppVersion) {
        // 数据校验
        RetResult ret = sysAppVersionService.isValid(sysAppVersion);
        if (!ret.getCode().equals(RetResult.SUCCESS)) {
            return ret;
        }

        if (StrUtil.isEmpty(sysAppVersion.getId())) {
            // 新增
            sysAppVersionService.insert(sysAppVersion);
        } else {
            // 更新
            sysAppVersionService.update(sysAppVersion);
        }
        return RetResult.ok();

    }

    /**
     * 批量删除APP版本表
     */
    @ApiOperation("批量删除APP版本表")
    @ResponseBody
    @PostMapping("/delete")
    @RequestLogHeader(modular = "APP版本表管理", businessType = "批量删除")
    public RetResult<?> delete(@RequestBody SysAppVersionDTO sysAppVersion) {
        return RetResult.ok(sysAppVersionService.removeBigBatch(sysAppVersion.getIds()));
    }


    /**
     * 上传app版本
     */
    @PostMapping("/upload")
    public RetResult<?> upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new CustomException("请上传Android（apk）安装包");
        }
        return appUploadFile("apk", file);
    }

    @PostMapping("/latestAppDownloadUrl")
    @AllowAnonymous
    public RetResult<?> latestAppDownloadUrl(@RequestBody SysAppVersionDTO dto) {
        QueryWrapper<SysAppVersion> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted", 0);
        wrapper.eq("enabled", 1);
        wrapper.eq("terminal_type", dto.getTerminalType());
        wrapper.orderByDesc("create_time");
        wrapper.last("limit 1");
        return RetResult.ok(sysAppVersionService.getOne(wrapper));
    }

    /**
     * app执行上传
     *
     * @param folder1 文件路径
     * @param file    文件
     * @return
     * @throws Exception
     */
    private RetResult<?> appUploadFile(String folder1, MultipartFile file) throws Exception {
        String path = storagePath + "/" + folder1;
        // 文件名
        String originalFilename = file.getOriginalFilename();
        // 扩展名
        String fileExtensions = FileUtil.getSuffix(originalFilename);

        if (!"apk".equals(fileExtensions.toLowerCase())) {
            // 返回
            return RetResult.fail("上传的文件格式不合法");
        }

        String saveFileName = IdUtils.snowflakeId() + "." + fileExtensions;
        if (!FileUtil.exist(path)) {
            FileUtil.mkdir(path);
        }

        file.transferTo(new File(path + "/" + saveFileName));

        String apkpath = path + "/" + saveFileName;
        Map<String, Object> data = new HashMap<>();

        try (ApkFile apkFile = new ApkFile(new File(apkpath))) {
            ApkMeta apkMeta = apkFile.getApkMeta();
            data.put("src", folder1 + "/" + saveFileName);
            data.put("versionCode", apkMeta.getVersionCode());
            data.put("versionName", apkMeta.getVersionName());
            data.put("totalSize", file.getSize());
            // FIX: 为什么用R
            return RetResult.ok(data);
        } catch (Exception e) {
            throw e;
        }
    }

}
